package com.lmoumou.lib_domian.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.lmoumou.lib_domian.DomainLauncher
import com.lmoumou.lib_domian.R
import kotlinx.android.synthetic.main.actvity_domain.*
import kotlinx.android.synthetic.main.domain_item.view.*

/**
 * 作者：Lmoumou
 * 时间：2020/8/11 10:27
 */
class DomainActivity : AppCompatActivity() {

    private val mInflater by lazy { LayoutInflater.from(this) }
    private val prefrence by lazy { getSharedPreferences("domain_content", Context.MODE_PRIVATE) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.actvity_domain)

        mEditText.setText(getString())

        btGo.setOnClickListener {
            val domain = "${mEditText.text}"
            if (!TextUtils.isEmpty(domain)) {
                //保存本次编辑的内容
                putString(domain)
                //回调domain变更接口
                DomainLauncher.getInstance().settingChangeCallback?.onDomainChange(domain)
                //启动APPLaunche页面
                startActivity(Intent(this, DomainLauncher.getInstance().launcherActivity))
                finish()
            } else {
                Toast.makeText(this, "请输入域名或者IP", Toast.LENGTH_SHORT).show()
            }
        }

        mRecyclerView.adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
            override fun onCreateViewHolder(
                parent: ViewGroup,
                viewType: Int
            ): RecyclerView.ViewHolder = object :
                RecyclerView.ViewHolder(mInflater.inflate(R.layout.domain_item, parent, false)) {}

            override fun getItemCount(): Int = DomainLauncher.getInstance().domains.size

            override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
                DomainLauncher.getInstance().domains[position].run {
                    holder.itemView.tvIP.text = ip
                    holder.itemView.tvName.text = name
                    holder.itemView.setOnClickListener {
                        mEditText.setText(ip)
                    }
                    null
                }
            }
        }
    }

    private fun putString(value: String) {
        val editor = prefrence.edit()
        editor.putString("domian_ip", value)
        editor.apply()
    }

    private fun getString(): String? {
        return prefrence.getString("domian_ip", "")
    }
}